package org.geektimes.projects.user.web.listener;

import org.geektimes.context.ClassicComponentContext;
import org.geektimes.context.ComponentContext;
import org.geektimes.projects.user.sql.DBConnectionManager;
import org.geektimes.web.WebApplicationInitializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import static org.geektimes.projects.user.sql.DBConnectionManager.*;

/**
 * 数据初始化
 * @author tom
 * @since 2021/3/30 16:21
 */
public class DbConfigInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        ComponentContext componentContext = ClassicComponentContext.getInstance();
        DBConnectionManager dbConnectionManager = componentContext.getComponent("bean/DBConnectionManager");
        Connection connection = dbConnectionManager.getConnection();
        Statement statement;
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            throw new ServletException(e.getMessage());
        }
        // 删除 users 表
        try {
            System.out.println(statement.execute(DROP_USERS_TABLE_DDL_SQL));
        }catch (Exception ignored){}
        // 创建 users 表
        try {
            System.out.println(statement.execute(CREATE_USERS_TABLE_DDL_SQL));
            System.out.println(statement.executeUpdate(INSERT_USER_DML_SQL));
        }catch (Exception ignored){}
    }
}
